#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2019 crane <crane@gosun>
#
# Distributed under terms of the MIT license.

"""

"""

class ClockWiseSnake:
    def proceed(self):
        self.row_up = self.margin
        self.row_down = self.row - self.row_up - 1

        if self.row_up > self.row_down :
            return False

        self.col_left = self.margin
        self.col_right = self.col - self.col_left - 1
        if self.col_left > self.col_right:
            return False

        return True

    def do_row_up(self, res):
        # 整行, 包括两边的边界
        for i in range(self.col_left, self.col_right+1):
            res.append( self.matrix[self.row_up][i] )

    def do_col_right(self, res):
        # 两行中间夹着的列, 不包括上下边界
        for i in range(self.row_up+1, self.row_down):
            res.append( self.matrix[i][self.col_right] )

    def do_row_down(self, res):
        # 整行, 包括边界

        if self.row_up == self.row_down:
            # self.row_up已经处理过, 不要重复处理
            return

        for i in range(self.col_right, self.col_left-1, -1):
            res.append( self.matrix[self.row_down][i] )

    def do_col_left(self, res):
        # 两行中间夹着的列, 不包括上下边界

        if self.col_left == self.col_right:
            # self.col_right中已经处理过了
            return

        for i in range(self.row_down-1, self.row_up, -1):
            res.append( self.matrix[i][self.col_left] )

    def clockwise_snake(self, matrix):
        self.matrix = matrix
        self.row, self.col = len(matrix), len(matrix[0])

        self.margin = 0

        res = []
        while self.proceed():
            self.do_row_up   (res)
            self.do_col_right(res)
            self.do_row_down (res)
            self.do_col_left (res)

            self.margin += 1

        return res


def test():
    l =  [1, 2, 3]
    l2 = [4, 5, 6]
    l3 = [7, 8, 9]
    l4 = ['a', 'b', 'c']
    l5 = ['d', 'e', 'f']

    m = [l, l2, l3, l4, l5]

    c = ClockWiseSnake()
    res = c.clockwise_snake(m)

    assert len(res) == len(m) * len(m[0])       # 测试
    print(res)

def main():
    print("start main")
    test()

if __name__ == "__main__":
    main()
